﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
namespace Admin.NET.Application;

/// <summary>
/// 人员信息服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class EmployeeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Employee> _employeeRep;
    public EmployeeService(SqlSugarRepository<Employee> employeeRep)
    {
        _employeeRep = employeeRep;
    }

    /// <summary>
    /// 分页查询人员信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询人员信息")]
    public async Task<SqlSugarPagedList<EmployeeOutput>> Page(EmployeeInput input)
    {
		input.SearchKey = input.SearchKey?.Trim();
        var query = _employeeRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.ZjEmpID.Contains(input.SearchKey)
                || u.Name.Contains(input.SearchKey)
                || u.IdNum.Contains(input.SearchKey)
                || u.Phone.Contains(input.SearchKey)
            )
            .WhereIF(input.ProjectId>0, u => u.ProjectId == input.ProjectId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.ZjEmpID), u => u.ZjEmpID.Contains(input.ZjEmpID.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.IdNum), u => u.IdNum.Contains(input.IdNum.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Phone), u => u.Phone.Contains(input.Phone.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Project>((u, projectid) => u.ProjectId == projectid.Id )
            .OrderBy(u => u.CreateTime)
            .Select((u, projectid) => new EmployeeOutput
            {
                Id = u.Id,
                ProjectId = u.ProjectId, 
                ProjectIdName = projectid.Name,
                ZjEmpID = u.ZjEmpID,
                Name = u.Name,
                IdNum = u.IdNum,
                Age = u.Age,
                Sex = (GenderEnum)u.Sex,
                Nation = u.Nation,
                Birthday = u.Birthday,
                Address = u.Address,
                Native = u.Native,
                Phone = u.Phone,
                Facephoto = u.Facephoto,
                WorkType = u.WorkType,
                WorkGroup = u.WorkGroup,
                EmerPeople = u.EmerPeople,
                EmerPhone = u.EmerPhone,
                Culture = u.Culture,
                Health = u.Health,
                QianFaJiGuan = u.QianFaJiGuan,
                IDcard_A = u.IDcard_A,
                IDcard_B = u.IDcard_B,
                QiXianQiShi = u.QiXianQiShi,
                QiXianShiXiao = u.QiXianShiXiao,
                BankName = u.BankName,
                BankAccount = u.BankAccount,
                IsAutoAudit = u.IsAutoAudit,
                IsMobile = u.IsMobile,
                MobileAccount = u.MobileAccount,
                MobilePassword = u.MobilePassword,
                PicLen = u.PicLen,
                TenantId = u.TenantId,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                IsSendClient = u.IsSendClient,
                SendClientErr = u.SendClientErr,
            });
        return await query.OrderBuilder(input, "u.").ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加人员信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加人员信息")]
    public async Task<long> Add(AddEmployeeInput input)
    {
        var entity = input.Adapt<Employee>();
        await _employeeRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除人员信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除人员信息")]
    public async Task Delete(DeleteEmployeeInput input)
    {
        var entity = await _employeeRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _employeeRep.FakeDeleteAsync(entity);   //假删除
        //await _employeeRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新人员信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新人员信息")]
    public async Task Update(UpdateEmployeeInput input)
    {
        var entity = input.Adapt<Employee>();
        await _employeeRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取人员信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取人员信息")]
    public async Task<Employee> Detail([FromQuery] QueryByIdEmployeeInput input)
    {
        return await _employeeRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取人员信息列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取人员信息列表")]
    public async Task<List<EmployeeOutput>> List([FromQuery] EmployeeInput input)
    {
        return await _employeeRep.AsQueryable().Select<EmployeeOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取项目列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "ProjectProjectIdDropdown"), HttpGet]
    [DisplayName("获取项目列表")]
    public async Task<dynamic> ProjectProjectIdDropdown()
    {
        return await _employeeRep.Context.Queryable<Project>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }




}
